﻿using System;
using System.Text.RegularExpressions;
using System.Windows.Automation;
using QuickUIT.Utilities;

namespace QuickUIT
{
    /// <summary>
    /// Matches an <see cref="AutomationElement"/> via a regular expression pattern on a specified <see cref="AutomationProperty"/>.
    /// </summary>
    public class AutomationElementRegexSearchCondition : IAutomationElementSearchCondition
    {
        /// <summary>
        /// Gets the property to be matched.  
        /// </summary>
        public AutomationProperty Property
        {
            get { return _property; } 
        }

        /// <summary>
        /// Gets the pattern used for matching. 
        /// </summary>
        public object Value 
        { 
            get { return _pattern; }
        }

        private readonly AutomationProperty _property; 
        private readonly Regex _pattern; 

        /// <summary>
        /// Creates a new search condition which matches properties by a regular expression. 
        /// </summary>
        /// <param name="property">The property to match.</param>
        /// <param name="pattern">The regular expression to match the property by.</param>
        public AutomationElementRegexSearchCondition(AutomationProperty property, Regex pattern)
        {
            ValidationUtility.ValidateArgumentNotNull(property, "property");
            ValidationUtility.ValidateArgumentNotNull(pattern, "pattern"); 
            
            _property = property;
            _pattern = pattern; 
        }

        /// <summary>
        /// Indicates whether an <see cref="AutomationElement"/> matches the search condition.  
        /// </summary>
        /// <param name="element">The element to check.</param>
        /// <returns>True if the search condition matches a property on the element; otherwise, false.</returns>
        public bool Matches(AutomationElement element)
        {
            object rawValue = element.GetCurrentPropertyValue(_property);
            string currentValue = rawValue != null ? rawValue.ToString() : String.Empty;
            return _pattern.IsMatch(currentValue); 
        }

        /// <summary>
        /// Returns a string that represents the current object.
        /// </summary>
        /// <returns>A string that represents the current object.</returns>
        public override string ToString()
        {
            string property = Property.ProgrammaticName.Split('.')[1];
            string value = Value != null ? Value.ToString() : String.Empty;
            return String.Format("{0}=/{1}/", property.Replace("Property", String.Empty), value);
        }
    }
}
